'''
Created on Aug 27, 2013

@author: marchi
'''
import re

class MyDict(object):
    def __init__(self):
        self.W={};

    def __getitem__(self,str1):
        if self.W.has_key(str1):
            return self.W[str1];
        else:
            print 'Unknown keyword '

    def put(self,str1,str2,val):
        if self.W.has_key(str1):
            if self.W[str1].has_key(str2):
                self.W[str1][str2]+=val;
            else:
                self.W[str1][str2]=val;                
        else:
            self.W[str1]={str2: val};

    def get(self,str1,str2):
        if self.W.has_key(str1):
            if self.W[str1].has_key(str2):
                print self.W[str1][str2];
            else:
                print 'Unknown second keyword '
        else:
            print 'Unknown first keyword '
        
class IntRes(object):
    def __init__(self,filename):
        '''
        Constructor
        '''
        p=re.compile('^%\$IRes');
        self.Table=MyDict();
        self.count=0;
        self.all={};
        self.Nmax=0;
        ok=False;
        for line in open(filename):
            if p.match(line):
                if ok: self.count+=1; ok=False;
                LineL=line.replace('-',' ').replace(':',' ')
                LineL=LineL.split();

                if len(LineL) != 1:
                    Nmax=(len(LineL)-1)/3;
                    for o in range(Nmax):
                        offset=1+o*Nmax;
                        self.Table.put(LineL[0+offset],LineL[1+offset],float(LineL[2+offset]));
            else:
                ok=True;
    def Avg(self,n=1.0):
        Table={}
        mykeys1=self.Table.W.keys()
        for key1 in mykeys1:
            Table[key1]=self.Table[key1]
        for key1 in mykeys1:
            mykeys2=Table[key1].keys();
            for key2 in mykeys2:
                str=' %5s ' % (key1) + ' %5s  ' % (key2)  + ' %10.3f ' % (Table[key1][key2]/self.count/n)
                print str;
            
            
            
            


        